package com.zaozhuang.robot;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.client.android.Intents;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.tencent.wmpf.demo.utils.WMPFDemoUtil;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;
import com.tencent.wmpf.app.WMPFBoot;
import com.tencent.wmpf.cli.api.WMPF;
import com.tencent.wmpf.cli.api.WMPFApiException;
import com.tencent.wmpf.cli.api.WMPFMiniProgramApi;
import com.tencent.wmpf.cli.model.WMPFDevice;
import com.tencent.wmpf.cli.model.WMPFStartAppParams;
import com.zaozhuang.robot.request.PersonCheckMiniProgramInfoRequestBean;
import com.zaozhuang.robot.request.PersonCheckMiniProgramInfoResponseBean;
import com.zaozhuang.robot.request.PersonCheckQRCodeRequestBean;
import com.zaozhuang.robot.request.PersonCheckQRCodeResponseBean;
import com.zaozhuang.robot.request.PersonCheckQRCodeResultRequestBean;
import com.zaozhuang.robot.request.PersonCheckQRCodeResultResponseBean;
import com.zaozhuang.robot.request.PersonCheckResultRequestBean;
import com.zaozhuang.robot.request.PersonCheckResultResponseBean;
import com.zaozhuang.robot.request.SBRequestBean;
import com.zaozhuang.robot.request.SBResponseBean;
import com.zaozhuang.robot.schedulerequest.PeriodicRequestTask;
import com.zaozhuang.robot.utils.CameraManager;
import com.zaozhuang.robot.utils.CustomCaptureManager;
import com.zaozhuang.robot.utils.ZxingUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class QrCodeActivity extends Activity implements CustomCaptureManager.OnBarcodeResultListener {
    private CustomCaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;

    private Button mMiniProgramLaunchBtn;
    private EditText mMiniProgramAppIdText;
    private EditText mMiniProgramPathText;
    private ImageView mCaptureBitmapIV;
//    private CameraManager mCameraManager;
    Button qrCodeBtn ;
    Button identifyQrCodeBtn;
    TextView qrCodeInfo;
    TextView identifyQrCodeInfo;
    ImageView qrImg;
    int REQUEST_CODE_SCAN = 1000;
    int scanWay = 3;//1:IntentIntegrator 2:CaptureActivity 3:自定义逻辑，从视频流获取采集帧，传bitmap识别。最终项目用法
    public static final String WX_APP_ID = "wx21352c636fe1ca9c";//wx710ac067e316d503
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_code);
        mMiniProgramPathText = findViewById(R.id.mini_program_path_text);
        mMiniProgramAppIdText = findViewById(R.id.mini_program_app_id_text);
        mMiniProgramLaunchBtn = findViewById(R.id.mini_program_launch_btn);

        mCaptureBitmapIV = findViewById(R.id.capture_bitmap_iv);
        qrCodeBtn = (Button)findViewById(R.id.generate_qr_code_btn) ;
        identifyQrCodeBtn = (Button)findViewById(R.id.identify_qr_code_btn) ;

        qrCodeInfo = (TextView) findViewById(R.id.qr_code_info) ;
        identifyQrCodeInfo = (TextView) findViewById(R.id.qr_code_info2) ;

        qrImg = (ImageView) findViewById(R.id.qr_code_img) ;
        qrCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                generateQrCode();
            }
        });
        identifyQrCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(scanWay == 1){
                    IntentIntegrator integrator = new IntentIntegrator(QrCodeActivity.this);
                    integrator.setPrompt("扫描二维码");
                    integrator.setCameraId(1);  // 指定摄像头
                    integrator.setBarcodeImageEnabled(true); // 是否生成条码扫描的缩略图。
                    integrator.initiateScan();
                } else if (scanWay == 2){
                    Intent intent = new Intent(QrCodeActivity.this, CaptureActivity.class);
                    intent.putExtra("SCAN_CAMERA_ID", 1);  // 0为后置摄像头，1为前置摄像头
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else if (scanWay == 3){
                    capture.onResume();
                    barcodeScannerView.setVisibility(View.VISIBLE);
                }
            }
        });

        mMiniProgramLaunchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(QrCodeActivity.this, FastExperienceActivity.class));
                String appId = mMiniProgramAppIdText.getText().toString();
                String path = mMiniProgramPathText.getText().toString();
                WMPFStartAppParams startAppParams = new WMPFStartAppParams(appId, "", WMPFStartAppParams.WMPFAppType.APP_TYPE_RELEASE);
                try {
                    WMPF.getInstance().getMiniProgramApi().launchMiniProgram(startAppParams, false, WMPFMiniProgramApi.LandscapeMode.NORMAL);
                } catch (WMPFApiException e) {
                    throw new RuntimeException(e);
                }
            }
        });


        // 初始化摄像头管理器
//        mCameraManager = new CameraManager(this, CameraSelector.LENS_FACING_FRONT);
//        mCameraManager.setBitmapCallback(this);

        WMPFDemoUtil.INSTANCE.checkWMPFVersion(this);
//        initWMPFCli();

        //初始化无感二维码识别
        initDBV(savedInstanceState);
    }

    @Override
    public void onBarcodeResult(BarcodeResult result) {
        String resultText = result.getText();
        identifyQrCodeInfo.setText("识别的二维码结果为:" + resultText);
        Toast.makeText(this, "识别的二维码结果为:" + resultText, Toast.LENGTH_SHORT).show();
        Log.e("onBarcodeResult","" + resultText);
        capture.onPause();
        barcodeScannerView.setVisibility(View.INVISIBLE);

        if (resultText != null && !resultText.isEmpty()) {
            requestPersonInfoBySBCode(resultText);
        }
    }

    private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    //通过社保码获取个人信息
    private void requestPersonInfoBySBCode(String code) {
        String url = "http://120.220.83.9:8333/agent/chat/getQRcode";
        String json = gson.toJson(new SBRequestBean(code, "bjSFvpDyBKsldVDYJibe"));
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Log.e("potter","url111:"+url);
        Log.e("potter","body111:"+json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(QrCodeActivity.this, "通过社保码请求人员信息出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                if (response.isSuccessful()) {
                    SBResponseBean bean = gson.fromJson(json, SBResponseBean.class);
                    if (bean == null || bean.getCode() != 200) {
                        // 处理错误情况
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(QrCodeActivity.this, "通过社保码请求人员信息出错", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        // 处理成功情况
                        String name = bean.getName();
                        String idCard = bean.getIdNumber();
                        Log.e("potter","name:" + name + "   idCard:" + idCard);
                        requestCommitPersonCheckMiniProgram(name, idCard);
                    }
                } else {
                    // 处理错误情况
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(QrCodeActivity.this, "通过社保码请求人员信息出错", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    public static final String ROBOT_PERSON_API = "https://robotapi.zzrs.loginby.me/v1/";
    final String testName = "张三";
    final String testIDCard = "37020219900101001X";
    //请求人员核验信息提交接口
    private void requestCommitPersonCheckMiniProgram(String name, String idCard) {
        PersonCheckMiniProgramInfoRequestBean bean = new PersonCheckMiniProgramInfoRequestBean(
                "robot",
                "addreq",
                "调用小程序的 APPID",
                0,
                name,
                idCard,
                "调用路径格式为`pages/certification/byrobot/cert_{id}`，`id`取值 1 - 9 且与设备 ID 对应",
                1,null);
        PersonCheckMiniProgramInfoRequestBean beanTest = new PersonCheckMiniProgramInfoRequestBean(
                "robot",
                "addreq",
                WX_APP_ID,
                1,
                testName,
                testIDCard,
                "pages/certification/byrobot/cert_1",
                1,null);
        String json = gson.toJson(beanTest);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(QrCodeActivity.this, "请求添加人脸核验出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.e("QrCodeActivity requestCommitPersonCheckMiniProgram onResponse", response.toString());
//                Log.e("QrCodeActivity requestCommitPersonCheckMiniProgram onResponse body", response.body().string());
                String json = response.body().string();
                if (response.isSuccessful()) {
                    PersonCheckMiniProgramInfoResponseBean bean = gson.fromJson(json, PersonCheckMiniProgramInfoResponseBean.class);
                    if (bean == null || bean.getErrcode() != 0) {
                        // 处理错误情况
                        Toast.makeText(QrCodeActivity.this, "请求添加人脸核验失败", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理成功情况
                        String reqid = bean.getData().getReqid();
                        Log.e("QrCodeActivity requestCommitPersonCheckMiniProgram onResponse", "reqid: " + reqid);
                        requestCheckPersonCheckResult(reqid);
                    }
                } else {
                    // 处理错误情况
                    Toast.makeText(QrCodeActivity.this, "请求添加人脸核验出错", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void requestCheckPersonCheckResult(String reqid) {
        PersonCheckResultRequestBean bean = new PersonCheckResultRequestBean(
                "robot",
                "getresult",
                "调用小程序的 APPID",
                "调用路径格式为`pages/certification/byrobot/cert_{id}`，`id`取值 1 - 9 且与设备 ID 对应",
                reqid);

        PersonCheckResultRequestBean beanTest = new PersonCheckResultRequestBean(
                "robot",
                "getresult",
                WX_APP_ID,
                "pages/certification/byrobot/cert_1",
                reqid);
        String json = gson.toJson(beanTest);
        Log.e("requestCheckPersonCheckResult", "json = " +json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(QrCodeActivity.this, "请求人脸核验结果出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    PersonCheckResultResponseBean bean = gson.fromJson(response.body().string(), PersonCheckResultResponseBean.class);
                    if (bean == null || bean.getErrcode() != 0) {
                        // 处理错误情况
//                        Toast.makeText(QrCodeActivity.this, "请求添加人脸核验失败", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理成功情况
                        //0：未发起核验，1：核验完成无问题， -1：核验失败，2：请求已失效
                        String reqid = bean.getData().getStatus();

                    }
                } else {
                    // 处理错误情况
//                    Toast.makeText(QrCodeActivity.this, "请求添加人脸核验出错", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void requestQRCodeResult(String reqid) {
        PersonCheckQRCodeResultRequestBean bean = new PersonCheckQRCodeResultRequestBean(
                "robot",
                "getqrresult",
                "调用小程序的 APPID",
                reqid);

        PersonCheckQRCodeResultRequestBean beanTest = new PersonCheckQRCodeResultRequestBean(
                "robot",
                "getqrresult",
                WX_APP_ID,
                reqid);
        String json = gson.toJson(beanTest);
        Log.e("requestCheckPersonCheckResult", "json = " +json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(QrCodeActivity.this, "请求人脸核验结果出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    Log.e("QrCodeActivity requestQRCodeResult onResponse", json);
                    PersonCheckQRCodeResultResponseBean bean = gson.fromJson(json, PersonCheckQRCodeResultResponseBean.class);
                    if (bean == null || bean.getErrcode() != 0) {
                        // 处理错误情况
//                        Toast.makeText(QrCodeActivity.this, "请求添加人脸核验失败", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理成功情况
                        //0：未发起核验，1：核验完成无问题， -1：核验失败，2：请求已失效
                        String reqid = bean.getData().getStatus();

                    }
                } else {
                    // 处理错误情况
//                    Toast.makeText(QrCodeActivity.this, "请求添加人脸核验出错", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void requestQRCode(String testName, String testIDCard) {
        PersonCheckQRCodeRequestBean bean = new PersonCheckQRCodeRequestBean(
                "robot",
                "getqrcode",
                "调用小程序的 APPID",
                "1",
                "",
                "",
                "trial",
                450,
                false);

        PersonCheckQRCodeRequestBean beanTest = new PersonCheckQRCodeRequestBean(
                "robot",
                "getqrcode",
                WX_APP_ID,
                "1",
                testName,
                testIDCard,
                "trial",
                450,
                false);

        String json = gson.toJson(beanTest);
        Log.e("qrcode 请求二维码参数 json", "" +json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(QrCodeActivity.this, "请求人脸核验结果出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    PersonCheckQRCodeResponseBean bean = gson.fromJson(result, PersonCheckQRCodeResponseBean.class);
                    if (bean == null || bean.getErrcode() != 0) {
                        // 处理错误情况
//                        Toast.makeText(QrCodeActivity.this, "请求添加人脸核验失败", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理成功情况
                        //0：未发起核验，1：核验完成无问题， -1：核验失败，2：请求已失效
                        String reqid = bean.getData().getReqid();
                        String qrBuffer = bean.getData().getQr_buffer();
                        Log.e("qrcode 请求二维码结果 json", "" +result);
                        Log.e("QrCodeActivity requestCheckPersonCheckResult", "reqid = " +reqid + " : qrBuffer = " + qrBuffer);
//                        requestQRCodeResult(reqid);

                        new PeriodicRequestTask(isSuccess -> {
                            runOnUiThread(() -> Toast.makeText(QrCodeActivity.this, isSuccess ? "成功" : "失败", Toast.LENGTH_SHORT).show());
                        }).startPeriodicCheckQRCodeRequests(reqid);
                    }
                } else {
                    // 处理错误情况
//                    Toast.makeText(QrCodeActivity.this, "请求添加人脸核验出错", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initDBV(Bundle savedInstanceState) {
        Intent intent = getIntent();
        barcodeScannerView = findViewById(R.id.qr_scanner_dbv);
        capture = new CustomCaptureManager(this, barcodeScannerView, this);
        capture.initializeFromIntent(intent, savedInstanceState);
        capture.decode();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(scanWay == 1){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if(result != null) {
                if(result.getContents() == null) {
                    identifyQrCodeInfo.setText("Cancelled");
                } else {
                    identifyQrCodeInfo.setText("识别的二维码结果为:" + result.getContents());
                }
            }
        }
//        else{
//            if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
//                if (data != null) {
//                    String content = data.getStringExtra("SCAN_RESULT");
//                    identifyQrCodeInfo.setText("识别的二维码结果为："+content);
//                    // 处理扫描结果
//                }
//            }
//        }


    }
    private void generateQrCode(){
        // 参数：内容、尺寸、颜色等
        BitMatrix matrix = null;
        String content = "hello world,this is cmcc!";
        qrCodeInfo.setText(content);
        try {
            matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 400, 400);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
        Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.RGB_565);
        for (int i = 0; i < 400; i++) {
            for (int j = 0; j < 400; j++) {
                bitmap.setPixel(i, j, matrix.get(i, j) ? Color.BLACK : Color.WHITE);
            }
        }
        qrImg.setImageBitmap(bitmap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mCameraManager.shutdown();
        capture.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        requestPersonInfoBySBCode("9200000002635122930159");
        requestQRCode(testName, testIDCard);

//        new PeriodicRequestTask(isSuccess -> {
//            //周期请求结束
//        }).startPeriodicCheckPersonRequests("17448862351");
//        new PeriodicRequestTask().startPeriodicCheckQRCodeRequests("17448862351");
    }

    @Override
    protected void onPause() {
        super.onPause();
        capture.onPause();
        barcodeScannerView.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

    private void initWMPFCli() {
        WMPFDevice deviceInfo = getDeviceInfo();
        if (deviceInfo.getProductId() == 0) {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("请先在 QrCodeActivity 设置设备信息").setCancelable(false).setNegativeButton("退出", (dialog, which) -> {
                this.finish();
            }).show();
            return;
        }
        WMPFBoot.init(this, getDeviceInfo());
    }

    private WMPFDevice getDeviceInfo() {
        return new WMPFDevice(BuildConfig.HOST_APPID, 0, 0, "", "");
    }
}
